from flask import Flask
from flask_jwt_extended import JWTManager
from sqlalchemy import text

from app.config import BaseConfig
from app.config import register_logger
# 导入定义的蓝图
from app.controllers import user_controller
from app.controllers import stock_controller  # 导入 blueprint 实例
from app.controllers.predict_controller import predict_controller
from app.controllers.portfolio_controller import portfolio_controller
from app.controllers import fund_controller
from app.controllers import bond_controller
from app.controllers import forex_controller
from app.controllers import asset_controller
from app.controllers import transaction_controller
from app.controllers import risk_controller
from app.controllers import ai_controller
from app.controllers.news_controller import news_controller  # 修改导入路径
from app.controllers.alpha_controller import alpha_controller

from xgboost import XGBRegressor
# 导入定义的数据库句柄
from app.models import db

def create_app():
    app = Flask(__name__)

    # 导入配置
    app.config.from_object(BaseConfig)
    app.config['JSON_AS_ASCII'] = False

    print(app.config['SQLALCHEMY_DATABASE_URI'])

    # 将db与flask应用程序关联
    db.init_app(app)

    # 数据库预热
    with app.app_context():
        db.session.execute(text('SELECT 1'))
        db.session.close()

    # 初始化XGBoost（可选）
    try:
        XGBRegressor()  # 预加载模型库
    except Exception as e:
        app.logger.warning(f"XGBoost初始化警告: {str(e)}")

    # 配置jwt
    jwt = JWTManager(app)

    # 注册Blueprint，并分别指定前缀
    # NOTE 接口定义规范：同属于一个功能模块的接口应当有相似的前缀，以便于管理和维护
    app.register_blueprint(user_controller, url_prefix='/user')
    # 注册股票接口
    app.register_blueprint(stock_controller, url_prefix='/stock')

    app.register_blueprint(fund_controller, url_prefix='/fund')
    # 注册模型以及预测接口
    app.register_blueprint(predict_controller, url_prefix='/predict')
    # 注册投资组合蓝图
    app.register_blueprint(portfolio_controller, url_prefix='/portfolio')

    app.register_blueprint(bond_controller, url_prefix='/bond')

    app.register_blueprint(forex_controller, url_prefix='/forex')

    #注册因子与最大回撤蓝图
    app.register_blueprint(alpha_controller, url_prefix='/alpha')

    # 注册新闻模块蓝图
    app.register_blueprint(news_controller, url_prefix='/news')  

    app.register_blueprint(asset_controller, url_prefix='/asset')

    app.register_blueprint(transaction_controller, url_prefix='/transaction')

    app.register_blueprint(risk_controller, url_prefix='/risk')

    app.register_blueprint(ai_controller, url_prefix='/ai')
    # 配置日志
    app = register_logger(app)

    # 调试专用：打印所有已注册的路由
    for rule in app.url_map.iter_rules():
        print(rule)

    return app